package com.yndsoft.jc.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.yndsoft.jc.model.XYUpdate;
import com.yndsoft.jc.utils.DialogHelper;
import com.yndsoft.jc.MainActivity;
import com.yndsoft.jc.R;
import com.yndsoft.jc.utils.CommMethodUtils;
import com.yndsoft.jc.utils.NetHelper;
import com.yndsoft.jc.utils.SharedPreferencesUtils;
import com.yndsoft.jc.utils.UpdateService;
import com.yndsoft.jc.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.Bind;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016-08-02.
 */
// ┏┓　　　┏┓
// ┏┛┻━━━┛┻┓
// ┃　　　　　　　┃ 　
// ┃　　　━　　　┃
// ┃　┳┛　┗┳　┃
// ┃　　　　　　　┃
// ┃　　　┻　　　┃
// ┃　　　　　　　┃
// ┗━┓　　　┏━┛
// ┃　　　┃ 神兽保佑　　　　　　　　
// ┃　　　┃ 代码无BUG！
// ┃　　　┗━━━┓
// ┃　　　　　　　┣┓
// ┃　　　　　　　┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫　┃┫┫
// ┗┻┛　┗┻┛
//public class WelcomeActivity extends Activity {
public class WelcomeActivity extends BaseActivity {
    @Bind(R.id.welcome_activity_img_init)
    CircleImageView welcome_activity_img_init;

    public Boolean checkupdate = false;
    public String VersionName = "";
    public int VersionCode = 0;
    public int UpdateVersionCode = 0;
    public String url_version;
    public Dialog dialog;
    public ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        //dialog = DialogHelper.createLoadingDialog(this);
        if (NetHelper.hasNetwork(WelcomeActivity.this)) {
            first_init();
        } else {
            init();
        }
    }

    public void first_init() {
        //首次启动
        try {
            //getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageManager packageManager = getPackageManager();
            PackageInfo pi = packageManager.getPackageInfo(getPackageName(), 0);
            // 获取版本号(内部识别号)
            VersionName = pi.versionName;
            VersionCode = pi.versionCode;
            //GetUpdate();
            init();

            // 弹出安装进度条对话框
            //pd = new ProgressDialog(WelcomeActivity.this);
            //pd.setCancelable(false);// 必须一直下载完，不可取消
            //pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            //pd.setMessage("正在下载新版本，请稍后...");
            //pd.setTitle("发现新版本");
            //pd.show();
            //down("http://system.moviejh.com/电影江湖.apk");
        } catch (PackageManager.NameNotFoundException ex) {
            Toast.makeText(WelcomeActivity.this, "查询新版本错误：" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            init();
        }
        //init_0();
    }

    public void weixin_init(Intent intent_getvalue) {
        //微信浏览器启动
        Uri uri = intent_getvalue.getData();
        // 完整的url信息
        String url = uri.toString();
        //获取指定参数值
        String type = uri.getQueryParameter("type");
        String id = uri.getQueryParameter("id");
        switch (type) {
            case "privatesingleday":
                //Intent intent_privatesingleday = new Intent(WelcomeActivity.this, PrivateSingleDayGuessActivity.class);
                //intent_privatesingleday.putExtra("id", id);
                //startActivity(intent_privatesingleday);
                //WelcomeActivity.this.finish();
                break;
            default:
                break;
        }
    }

    public void init_0() {
        //Intent intent = new Intent(WelcomeActivity.this, TestTreeActivity.class);
        //Intent intent = new Intent(WelcomeActivity.this, WXEntryActivity.class);
        //Intent intent = new Intent(WelcomeActivity.this, TestUptrActivity.class);
        //startActivity(intent);
        //WelcomeActivity.this.finish();
    }

    public void init() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                startActivity(intent);
                WelcomeActivity.this.finish();
            }
        }, 1500);


//        final boolean firsttimeUse = SharedPreferencesUtils.getInstance().getBoolean("xiaoyao-firsttime-use", true);
//        //Toast.makeText(WelcomeActivity.this, firstTimeUse == true ? "true" : "false", Toast.LENGTH_LONG).show();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (firsttimeUse) {
//                    Animation fadeOut = AnimationUtils.loadAnimation(WelcomeActivity.this, R.anim.fadeout);
//                    fadeOut.setFillAfter(true);
//                    activity_welcome_img.startAnimation(fadeOut);
//                    Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
//                    startActivity(intent);
//                    WelcomeActivity.this.finish();
//                } else {
//                    Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
//                    startActivity(intent);
//                    WelcomeActivity.this.finish();
//                }
//            }
//        }, 2000);
    }

    //android 的一个倒计时功能
    public void DownTime() {
        //TextView countDown =  (TextView) findViewById(R.id.count_down);
        //CountDownTimer构造器的两个参数分别是第一个参数表示总时间，第二个参数表示间隔时间。
        //意思就是每隔xxx会回调一次方法onTick，然后xxx之后会回调onFinish方法。
        CountDownTimer timer = new CountDownTimer(3000, 1000) {
            int num = 2;

            @Override
            public void onTick(long millisUntilFinished) {
                //设置数字递减
                //countDown.setText(String.valueOf(num));
                num--;
            }

            @Override
            public void onFinish() {
                //计时完成调用
                //Intent i = new Intent(WelcomeActivity.this, SecondActivity.class);
                //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                //startActivity(i);
                //finish();
            }
        };
        timer.start();
    }

    public void GetUpdate() {
        url_version = getString(R.string.url_version);
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url_version)
                    .get()
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException ex) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WelcomeActivity.this, "检查新版本出错!", Toast.LENGTH_SHORT).show();
                            init();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final InputStream stream = response.body().byteStream();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final XYUpdate update = CommMethodUtils.parseUpdateXml(stream);
                            if (update != null) {
                                if (update.getVersion() > VersionCode) {
                                    try {
                                        Dialog alertDialog = new AlertDialog.Builder(WelcomeActivity.this)
                                                .setTitle("提示")
                                                .setMessage("服务器有新版本，需要更新吗？")
                                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int which) {
                                                        //通知栏进行更新
                                                        Intent intent = new Intent(WelcomeActivity.this, UpdateService.class);
                                                        intent.putExtra("AppUpdateUrl", update.getUrl());
                                                        startService(intent);
                                                        init();
                                                        //普通跳转
                                                        //Uri uri = Uri.parse(update.getUrl());
                                                        //Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                                        //startActivity(it);
                                                        //WelcomeActivity.this.finish();
                                                        //dialog.show();
                                                    }
                                                })
                                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        init();
                                                    }
                                                }).create();
                                        alertDialog.show();
                                    } catch (Exception ex) {
                                        Toast.makeText(WelcomeActivity.this, "出错：" + ex.getMessage(), Toast.LENGTH_LONG).show();
                                    }
                                } else {
                                    init();
                                }
                            } else {
                                init();
                            }
                        }
                    });
                }
            });
        } catch (Exception ex) {
            Toast.makeText(WelcomeActivity.this, "检查新版本出错：" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            init();
        }
    }

    public void down(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException arg1) {
                Toast.makeText(WelcomeActivity.this, "下载失败", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String DM_TARGET_FOLDER = File.separator + "MovieJH" + File.separator; //下载目标文件夹
                String destFileDir;     //目标文件存储的文件夹路径
                String destFileName;    //目标文件存储的文件名
                destFileDir = Environment.getExternalStorageDirectory() + DM_TARGET_FOLDER;
                destFileName = "电影江湖.apk";
                File dir = new File(destFileDir);
                if (!dir.exists()) dir.mkdirs();
                final File file = new File(dir, destFileName);
                if (file.exists()) file.delete();

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();

                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        pd.setProgress(progress);
                    }
                    fos.flush();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 结束掉进度条对话框
                            pd.dismiss();
                            //下载成功
                            //EventBus.getDefault().post("ApkDownSuccess");
                            //dialog.dismiss();
                            //Toast.makeText(WelcomeActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                            //CommMethodUtils.installApk(WelcomeActivity.this, file);
                        }
                    });
                } catch (final Exception ex) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WelcomeActivity.this, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException ex) {
                        Toast.makeText(WelcomeActivity.this, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException ex) {
                        Toast.makeText(WelcomeActivity.this, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    //未测试 --- 2016.11.11
    /*
     * 从服务器中下载APK
	 */
    protected void downLoadApk() {
        final ProgressDialog pd;    //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = CommMethodUtils.getFileFromServer("url", pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    Message msg = new Message();
                    //msg.what = DOWN_ERROR;
                    //handler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
}